from knox.views import LoginView as KnoxLoginView
from main.serializers import LoginUserSerializer, UserSerializer
from rest_framework import generics, permissions, serializers


class LoginAPIView(KnoxLoginView):
    permission_classes = (permissions.AllowAny,)

    def post(self, request, format=None):
        serializer = LoginUserSerializer(data=request.data)
        if serializer.is_valid(raise_exception=True) and (
            user := serializer.validated_data.get("user")
        ):
            request.user = user
            return super().post(request, format=None)
        raise serializers.ValidationError("Invalid credentials")


class WhoAmIView(generics.RetrieveAPIView):
    permission_classes = (permissions.IsAuthenticated,)
    serializer_class = UserSerializer

    def get_object(self):
        return self.request.user
